using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
//using System.Windows.Data;
using Microsoft.Xaml.Behaviors;
using WPFTemplateLib.WpfHelpers;

namespace WPFTemplateLib.Behaviors
{
	/// <summary>
	/// 选中集合行为类
	/// <para/>修改自：《[WPF 中如何将多选项目的 SelectedItems 属性绑定到 ViewModel](https://www.bilibili.com/video/BV1HM411k76b/)》
	/// https://gist.github.com/BYJRK/33932133a6fc1951d3a935b8f30b2d79
	/// </summary>
	/// <example>
	///	<![CDATA[
	///	<b:Interaction.Behaviors>
	///		<lib:SelectedItemsBehavior BindableSelectedItems="{Binding SelectedItemsForBehavior, Mode=OneWayToSource}"
	///				SelectedItemsChangedCommand="{Binding SelectedItemsChangedCmd}"/>
	///	</b:Interaction.Behaviors>
	/// ]]>
	/// </example>
	public class SelectedItemsBehavior : Behavior<MultiSelector>
	{
		protected override void OnAttached()
		{
			base.OnAttached();

			AssociatedObject.SelectionChanged += OnSelectionChanged;
		}

		protected override void OnDetaching()
		{
			base.OnDetaching();

			AssociatedObject.SelectionChanged -= OnSelectionChanged;
		}

		private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			var selector = (MultiSelector)sender;
			var items = selector.SelectedItems;

			BindableSelectedItems = items;
			//var bindingExp = BindingOperations.GetBindingExpression(this, BindableSelectedItemsProperty);
			//bindingExp?.UpdateSource();

			SelectedItemsChangedCommand?.Execute(items);
		}

		#region 依赖属性

		#region [依赖属性] 可绑定的选中项集合
		/// <summary>
		/// [依赖属性] 可绑定的选中项集合
		/// </summary>
		public IList BindableSelectedItems
		{
			get => (IList)GetValue(BindableSelectedItemsProperty);
			set => SetValue(BindableSelectedItemsProperty, value);
		}
		public static readonly DependencyProperty BindableSelectedItemsProperty =
			DependencyProperty.Register(nameof(BindableSelectedItems), typeof(IList), typeof(SelectedItemsBehavior), new PropertyMetadata(null));
		#endregion

		#region [依赖属性] 选中项集合变动命令
		/// <summary>
		/// [依赖属性] 选中项集合变动命令（需绑定 RelayCommand&lt;IList&gt; 类型命令）
		/// </summary>
		public RelayCommand<IList> SelectedItemsChangedCommand
		{
			get => (RelayCommand<IList>)GetValue(SelectedItemsChangedCommandProperty);
			set => SetValue(SelectedItemsChangedCommandProperty, value);
		}
		public static readonly DependencyProperty SelectedItemsChangedCommandProperty =
			DependencyProperty.Register(nameof(SelectedItemsChangedCommand), typeof(RelayCommand<IList>), typeof(SelectedItemsBehavior), new PropertyMetadata(null));
		#endregion

		#endregion
	}
}
